﻿using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using static NPOI.HSSF.Util.HSSFColor;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;


namespace Module_Debug.Others
{
    public partial class JEITAdata : Form
    {
        public JEITAdata(frmMain Frm)
        {
            MainForm = Frm;
            InitializeComponent();
        }
        frmMain MainForm = null;
        frmMain frmTop = null;

        private string[,] Flickerdata_input;
        private int datalength = 8192;
        private double DATAFrequency = 0;       // 刷新率
        private double DATAFlicker = 0;
        private int DATAEMpluse = 12;           // EM pulse 数
        private double T_Period = 0.0;          // 一帧时间
        private double deltatime = 0.0;         // 数据的采样间隔时间
        private int deltatimenums = 0;          // 一帧内的数据采样数 600
        private int T_nums = 12;                // datalength 数据长度内的周期数 （帧数）
        private double timenums = 0;
        private int EMtimenums = 0;             // 1 EM pulse内 的采样数据数50
        private int ChangeTimes = 0;
        private double YlistMin = 0.0;
        private double YlistMax = 0.0;
        private int starpulse = 2;
        private uint waveformdatasize = 0;
        private double measurementtime = 0;
        private double[] wavedata;
        private double[] weightingwavedata;
        private int[] Datapositmax;
        private double[] DataFlickermax;
        private byte[] Send_buf ;
        private int[] Xnumslist;
        private int samplingcount;
        private byte[] EMaddr;
        private byte[] TXTVablebyte;
        private string[] Txvabletxt;
        private byte[] Txvable;
        private byte DDICReg;
        private byte readnum;
        const byte CodelengthValue = 0x02;
        const int FirstDataLine = 10;

        private Flicker flicker = new Flicker();
        CRC16 CRCData = new CRC16();

        private void Flickerdata_analysis_FormClosing(object sender, EventArgs e)
        {
            frmMain.frmain.Flickerdata_form = null;
        }
        private void Open_CSV(string path)
        {
            try
            {
                int line_count = 0;
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string strLine = streamReader.ReadLine();
                string[] aab = strLine.Split(',');

                Flickerdata_input = new string[(int)datalength + (int)datalength, aab.Length];

                while (!string.IsNullOrEmpty(strLine))
                {
                    aab = strLine.Split(',');
                    for (int i = FirstDataLine; i < aab.Length; i++)
                    {
                        Flickerdata_input[line_count, i] = aab[i];
                    }
                    strLine = streamReader.ReadLine(); //循环读取下一行
                    line_count++;

                }
                fs.Close(); //关闭流
                streamReader.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("文件被其他应用打开，请关闭对该文件的引用！！！");
            }
        }
        private void OpenExcel(string path)//NPIO打开excel
        {
            IWorkbook Workbook;
           try
           {
                using (FileStream fs = File.OpenRead(path))   //打开myxls.xls文件
                Workbook = new XSSFWorkbook(fs);   //把xls文件中的数据写入wk中
                ISheet Worksheet = null;

                for (int i = 0; i < Workbook.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中总共的表数
                {
                    Worksheet = Workbook.GetSheetAt(i);   //读取当前表数据
                                                          //  v datarow = Worksheet.LastRowNum;
                                                          //    ISheet Worksheet = Workbook.GetSheetAt((int)Excelsheet.Value);   //读取表数据

                    for (int j = 0; j <= Worksheet.LastRowNum; j++)  //LastRowNum 是当前表的总行数
                    {
                        IRow row = Worksheet.GetRow(j);  //读取当前行数据

                        if (j == 0)
                        {
                            MessageBox.Show("数据有误");
                        }
                        if (row != null)
                        {
                            for (int k = FirstDataLine; k <= row.LastCellNum; k++)  //LastCellNum 是当前行的总列数
                            {
                                ICell cell = row.GetCell(k);  //当前表格
                                if (cell != null)
                                {
                                    Flickerdata_input[j, k] = Convert.ToString(cell);
                                }
                            }
                        }
                    }
                }
           }
           catch (Exception)
           {
              MessageBox.Show("文件被其他应用打开，请关闭对该文件的引用！！！");
           }
        }
        private void OpenCSVcheck_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;//设定只允许打开一个文件

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.Text += openFileDialog.FileName;
                string Alastname = openFileDialog.FileName.Substring(openFileDialog.FileName.LastIndexOf(".") + 1).ToUpper();
                var filePath = openFileDialog.FileName;//
                                                       //            Flicker_data = openFileDialog.SafeFileName.Substring(0, openFileDialog.SafeFileName.LastIndexOf("."));
                if (string.IsNullOrEmpty(filePath)) return;//判断选择的文件名称是不是空
                try
                {

                    if (Alastname == "CSV")
                    {
                        Open_CSV(openFileDialog.FileName);
                        MessageBox.Show("数据载入完成");

                    }
                    else if (Alastname == "XLSX")
                    {
                       OpenExcel(openFileDialog.FileName);
                    }
                    else
                    {
                        MessageBox.Show("选中的" + Alastname + "格式不在兼容范围内");
                    }
                }
                catch
                {
                    MessageBox.Show("打开文件失败");
                }
            }
            else
            {
                return;
            }
        }
        private void DataDrawing()
        {
            try
            {
                DataGridViewColumn col;
                DataGridViewRow row;
                DataGridViewCell cell = new DataGridViewTextBoxCell();
                for (int i = 0; i < DATAEMpluse - 1; i++)
                {
                    row = new DataGridViewRow();
                    FlickerDeltaPer.Rows.Add(row);
                    FlickerDeltaPer.Rows[i].Cells[0].Value = i + 1;
                    FlickerDeltaPer.Rows[i].Cells[1].Value = DataFlickermax[i].ToString("#0.00000");
                }
                FlickerDeltaPer.ClearSelection();
                this.FlickerDeltaPer.RowHeadersVisible = false;

                datachart.Series[0].Points.DataBindXY(Xnumslist, weightingwavedata);
                datachart.Series[1].Points.DataBindXY(Datapositmax, DataFlickermax);

                datachart.ChartAreas[0].AxisX.Maximum = Math.Min(datalength, Convert.ToInt32(XlistMax.Text));
                datachart.ChartAreas[0].AxisX.Minimum = 0;

                datachart.ChartAreas[0].AxisY.Maximum = Math.Floor(YlistMax * 10 + 1) / 10;
                datachart.ChartAreas[0].AxisY.Minimum = Math.Floor(YlistMin * 10) / 10;

                datachart.ChartAreas[0].AxisX.Title = " ";
                datachart.ChartAreas[0].AxisY.Title = " ";

                datachart.Legends[0].Enabled = false;
            }
            catch (Exception)
            {
                MessageBox.Show("绘制数据有误，请重新测量计算");
            }
        }
        private byte[] GetCRCArray_Flicker(byte[] arr, Byte speedflag)   //处理命令数组，在其头尾增加包头(9F,在一个包内包含多行code)以及CRC校验值，处理后的数据可以直接发送至下位机
        {
            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;//格式：9f,speedflag(高低速),有效数据长度+1,一行code长度，一行code内容（多个Byte），一行code长度，一行code内容。。。，0xFF(结束标志位),crc1,crc2。
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }
        private void DataMeasure()       // 测量
        {
            switch (SamplingNumber.SelectedIndex)
            {
                case 0:  //8192
                    samplingcount = 13; // 8192
                    break;
                case 1:
                    samplingcount = 12; // 4096
                    break;
                case 2:
                    samplingcount = 11; // 2048
                    break;
                case 3:
                    samplingcount = 10; // 1024
                    break;
                default:
                    samplingcount = 13; // 8192
                    break;
            }

            try
            {
                this.datachart.Enabled = false;
                this.datachart.Text = "Waiting ...";

                flicker.get_WaveformMeasure(samplingcount, ref wavedata, ref weightingwavedata, ref measurementtime, ref waveformdatasize);
//                flicker.get_flicker(ref DATAFlicker, ref DATAFrequency);

                deltatime = measurementtime / waveformdatasize;                                  //数据的采样间隔时间
                datalength = (int)waveformdatasize;

 //               this.Freqdata.Text = DATAFrequency.ToString("#0.000");
 //               this.flickerdata.Text = DATAFlicker.ToString("#0.00");

                this.datachart.Enabled = true;
                this.datachart.Text = "采集";
            }
            catch (Exception)
            {
                MessageBox.Show("请确认CA410在JEITA模式下0Cal");
            }
        }
        private void DataCodeWrite_Click(object sender, EventArgs e)
        {
            try
            {
                var dataBytes = new List<byte>();

                // 1. add pluse
                AddPulseData(PulsePage, CodelengthValue, dataBytes);

                // 2. 处理12个pulse
                var pulseControls = new[] { PulseNo1, PulseNo2, PulseNo3, PulseNo4, PulseNo5, PulseNo6,
                                  PulseNo7, PulseNo8, PulseNo9, PulseNo10, PulseNo11, PulseNo12 };

                foreach (var control in pulseControls)
                {
                    AddPulseData(control, CodelengthValue, dataBytes);
                }

                // 3. write code
                byte[] finalData = dataBytes.ToArray();
                frmMain.frmain.comPort.Write(GetCRCArray_Flicker(finalData, 4), 0, finalData.Length + 6);

            }
            catch (FormatException ex)
            {
                MessageBox.Show($"十六进制格式错误：{ex.Message}");
            }
            catch (IndexOutOfRangeException)
            {
                MessageBox.Show("输入值需要两个以逗号分隔的十六进制数");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败：{ex.Message}");
            }
        }
        private void AddPulseData(Control control, byte prefix, List<byte> buffer)
        {
            var parts = GetValidatedHexValues(control);
            buffer.Add(prefix);
            buffer.AddRange(parts);
        }
        private byte[] GetValidatedHexValues(Control control)
        {
            string[] parts = control.Text.Split(',');

            if (parts.Length < 2)
            {
                throw new FormatException($"{control.Name} 需要两个以逗号分隔的值");
            }

            return new[] {
        ParseHexByte(parts[0], control.Name),
        ParseHexByte(parts[1], control.Name)
    };
        }        
        private byte ParseHexByte(string value, string controlName)
        {
            if (byte.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte result))
            {
                return result;
            }
            throw new FormatException($"{controlName} 包含无效的十六进制值: {value}");
        }  
        private void Save_as_Click(object sender, EventArgs e)            // csv保存
        {
            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型
            string str = "Data" + "\r\n";
            str = str + "Time" + "\r\n";
            str = str + "Sampling Number" + "," + datalength.ToString() + "," + "Flicker (JEITA) [dB]" + "," + DATAFlicker.ToString() + "\r\n";
            str = str + "Weighting Factor" + "," + "JEITA" + "," + "Detected Freq. [Hz]" + "," + DATAFrequency.ToString() + "\r\n";
            str = str + "Decimation Interval" + "\r\n";
            str = str + "Flicker Output Sensor" + "\r\n";
            str = str + "Light Receiving Sensor" + "\r\n";

            str = str + "\r\n";
            str = str + "Time [sec],Data,weighted Data\r\n";

            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                    for (int i = 0; i < datalength; i++)
                    {
                        str = str + (measurementtime * i / datalength).ToString() + "," + wavedata[i].ToString() + "," + weightingwavedata[i].ToString() + "\r\n";
                    }
                    sw.WriteLine(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                }
                catch
                {
                    MessageBox.Show("数据保存时发生错误，请重试");
                }
            }

        }
        private void RefreshPulse(byte[] inputPulse)
        {
            if (inputPulse == null) return;

            const int startIndex = 4;   // 
            const int indexStep = 3;    // 
            const int pairCount = 12;   // pulse数量

            var pulseControls = new[]
            {
               PulseNo1, PulseNo2, PulseNo3, PulseNo4, PulseNo5, PulseNo6,
               PulseNo7, PulseNo8, PulseNo9, PulseNo10, PulseNo11, PulseNo12
            };

            for (int i = 0; i < pairCount; i++)
            {
                int baseIndex = startIndex + i * indexStep;

                if (baseIndex + 1 >= inputPulse.Length)
                {
                    throw new IndexOutOfRangeException($"输入数组长度不足，需要至少 {baseIndex + 2} 字节");
                }

                //pulseControls[i].Text = FormatBytePair(inputPulse[baseIndex],inputPulse[baseIndex + 1]);


                SetPulseValue(pulseControls[i], inputPulse[baseIndex], inputPulse[baseIndex + 1]);

            }
        }
        //private static string FormatBytePair(byte first, byte second)
        //{
         //   return $"{first:X2},{second:X2}";
        //}
        private void LoadPulse()
        {
            if (EMaddr != null && ChangeTimes != 0)
                return;

            try
            {
                var buffer = new List<byte>();

                // 处理特殊页地址
                AddPulseData(PulsePage, CodelengthValue, buffer);

                // 处理所有pulse通道
                var pulseControls = new[] { PulseNo1, PulseNo2, PulseNo3, PulseNo4, PulseNo5, PulseNo6,
                                  PulseNo7, PulseNo8, PulseNo9, PulseNo10, PulseNo11, PulseNo12 };

                foreach (var control in pulseControls)
                {
                    AddPulseData(control, CodelengthValue, buffer);
                }

                EMaddr = buffer.ToArray();
            }
            catch (Exception)
            {
                MessageBox.Show("Code load 失败，请检查格式");
            }
        }
        private bool TryParsePercentage(TextBox textBox, out double result)
        {
            string cleanText = textBox.Text.Replace("%", "");
            return double.TryParse(cleanText, NumberStyles.Any, CultureInfo.InvariantCulture, out result);
        }
        private void AutoMeasure_Click(object sender, EventArgs e)
        {
            EMaddr = null;
            ChangeTimes = 0;
            LoadPulse();
            frmMain.frmain.comPort.Write(GetCRCArray_Flicker(EMaddr, 4), 0, EMaddr.Length + 6);
            Auto();
        }
        private void Auto()
        {
            DataMeasure();
            DataCount();
            DataDrawing();
            DataDetermine(DataFlickermax);
        }
        private void MeasureCount_Click(object sender, EventArgs e)
        {
            DataMeasure();

            flicker.get_flicker(ref DATAFlicker, ref DATAFrequency);
            this.Freqdata.Text = DATAFrequency.ToString("#0.000");
            this.flickerdata.Text = DATAFlicker.ToString("#0.00");

            DataCount();
            DataDrawing();
        }
        private void PulseTxTLoad(string FilePath) //输入脚本路径，载入脚本写入UI
        {
            if (File.Exists(FilePath))
            {
                FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("UTF-8"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string str_generate = streamReader.ReadLine();
                //循环读取文本信息
                try
                {
                    while (str_generate != null)
                    {
                        int index = str_generate.IndexOf("//");
                        if (index != -1)
                        {
                            str_generate = str_generate.Remove(index);
                        }
                        str_generate = str_generate.Replace(" ", "");
                        char[] delimiterChars = { ',' };
                        Txvabletxt = str_generate.Split(delimiterChars);
                        Txvable = new byte[] { Convert.ToByte(Txvabletxt[0], 16), Convert.ToByte(Txvabletxt[1], 16) };
                        if (TXTVablebyte == null)
                        {
                            TXTVablebyte = Txvable;
                        }
                        else
                        {
                            TXTVablebyte = TXTVablebyte.Concat(Txvable).ToArray();
                        }
                        str_generate = streamReader.ReadLine(); //循环读取下一行
                    }
                }
                catch (Exception)
                {
                 MessageBox.Show("文本格式有误");
                }

                fs.Close(); //关闭流
                streamReader.Close();
                MessageBox.Show("载入完成");
            }
            else
            {
                MessageBox.Show("载入失败");
            }
        }
        private void Import_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                Filter = "配置文件(*.txt)|*.txt|所有文件(*.*)|*.*",
                Title = "选择配置文件"
            };

            if (ofd.ShowDialog() != DialogResult.OK) return;

            try
            {
                PulseTxTLoad(ofd.FileName);

                if (TXTVablebyte == null || TXTVablebyte.Length == 0)
                {
                    MessageBox.Show("配置文件内容为空!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var pulseControls = new[]
                {
                  PulseNo1, PulseNo2, PulseNo3, PulseNo4, PulseNo5, PulseNo6,
                  PulseNo7, PulseNo8, PulseNo9, PulseNo10, PulseNo11, PulseNo12
                };

                // 每个pulse需要2个字节，共需要24字节（12个pulse×2字节）
                int requiredBytes = pulseControls.Length * 2;

                if (TXTVablebyte.Length < requiredBytes)
                {
                    MessageBox.Show($"配置文件不完整，需要至少{requiredBytes}字节，当前只有{TXTVablebyte.Length}字节",
                                  "格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                for (int i = 0; i < pulseControls.Length; i++)
                {
                    int byteIndex = i * 2;
                    SetPulseValue(pulseControls[i], TXTVablebyte[byteIndex], TXTVablebyte[byteIndex + 1]);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("load失败，请检查格式");
            }
            finally
            {
                TXTVablebyte = null; // 清理资源
            }
        }
        private void SetPulseValue(Control control, byte byte1, byte byte2)
        {
            control.Text = $"{byte1:X2},{byte2:X2}";
        }
        private void Export_Click(object sender, EventArgs e)
        {
            if (PulseNo1.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
                return;
            }
            //创建保存对话框对象
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "gamma cfg files (*.txt)|*.txt"; //过滤文件类型
            save.FilterIndex = 1;
            save.RestoreDirectory = true;
            if (save.ShowDialog() == DialogResult.OK)
            {
                string path = save.FileName;
                save.DefaultExt = ".txt";
                StreamWriter sw = new StreamWriter(path);
                sw.WriteLine(PulseNo1.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo2.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo3.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo4.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo5.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo6.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo7.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo8.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo9.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo10.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo11.Text.Replace(" ", ""));
                sw.WriteLine(PulseNo12.Text.Replace(" ", ""));
                sw.Close();
            }
        }
        private void CodeToText_Click(object sender, EventArgs e)
        {
            try
            {
                //LOAD PUSLE
                var pulseControls = new[]
                {
                   PulseNo1, PulseNo2, PulseNo3, PulseNo4, PulseNo5, PulseNo6,
                   PulseNo7, PulseNo8, PulseNo9, PulseNo10, PulseNo11, PulseNo12
                };

                var sb = new StringBuilder(capacity: 12 * 8); // 预分配容量

                foreach (var control in pulseControls)
                {
                    // 移除空格并验证格式
                    var cleanValue = ValidateAndCleanInput(control.Text, control.Name);
                    sb.AppendLine(cleanValue);
                }

                // 设置最终文本（移除最后一个换行符）
                if (sb.Length > 0)
                {
                    sb.Length -= Environment.NewLine.Length;
                }
                TextCode.Text = sb.ToString();
            }
            catch (FormatException ex)
            {
                MessageBox.Show($"格式错误: {ex.Message}", "转换失败",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败: {ex.Message}", "错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private string ValidateAndCleanInput(string input, string controlName)
        {
            // 移除所有空格
            string cleanInput = input.Replace(" ", "");

            // 格式验证（XX,XX 十六进制格式）
            if (!Regex.IsMatch(cleanInput, @"^[0-9A-Fa-f]{2},[0-9A-Fa-f]{2}$"))
            {
                throw new FormatException($"{controlName} 包含无效格式: {input}");
            }

            return cleanInput;
        }
        private void TextToCode_Click(object sender, EventArgs e)
        {
            const int requiredLines = 12;
            var pulseControls = new[]
            {
                PulseNo1, PulseNo2, PulseNo3, PulseNo4, PulseNo5, PulseNo6,
                PulseNo7, PulseNo8, PulseNo9, PulseNo10, PulseNo11, PulseNo12
            };

            try
            {
                // 分割文本并验证行数
                var lines = TextCode.Text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                if (lines.Length < requiredLines)
                {
                    throw new FormatException($"需要至少{requiredLines}行有效数据，当前找到{lines.Length}行");
                }

                // 批量处理并验证格式
                for (int i = 0; i < pulseControls.Length; i++)
                {
                    var validatedValue = ValidateLineFormat(lines[i], i + 1);
                    pulseControls[i].Text = validatedValue;
                }
            }
            catch (FormatException ex)
            {
                MessageBox.Show($"格式错误: {ex.Message}", "转换失败",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败: {ex.Message}", "错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private string ValidateLineFormat(string line, int lineNumber)
        {
            // 移除空格并验证格式
            var cleanLine = line.Replace(" ", "");

            if (!Regex.IsMatch(cleanLine, @"^[0-9A-Fa-f]{2},[0-9A-Fa-f]{2}$"))
            {
                throw new FormatException($"第{lineNumber}行格式无效: {line}");
            }

            return cleanLine;
        }
        private void READCODE(string[] Pulse)
        {
            try
            {
                string[] PulseAddr = PulsePage.Text.Split(',');
                byte[] DataCode = new byte[]
                {
                2, Convert.ToByte(PulseAddr[0], 16), Convert.ToByte(PulseAddr[1], 16),       //FE,72
                };
                frmMain.frmain.comPort.Write(GetCRCArray_Flicker(DataCode, 4), 0, DataCode.Length + 6);

                readnum = 1;

                DDICReg = byte.Parse(Convert.ToUInt32(Pulse[0], 16).ToString());
                GeneralRegRead(DDICReg, readnum);
            }

            catch (Exception)
            {
                MessageBox.Show("Code格式有误");
            }
        }
        public void GeneralRegRead(byte DDICReg, byte ReturnNumber)   //通用读写
        {
            byte READ_flag = 0x26;
            byte MipiCommandModeSelect_Flag = 0;
            Send_buf = new byte[ReturnNumber + 6];
            Send_buf[1] = (byte)(READ_flag | MipiCommandModeSelect_Flag);   // 读写标志/读写速度模式
            Send_buf[2] = (byte)(ReturnNumber + 1);                         // length   //返回数据长度=（被读取的寄存器地址占用1byte）+有效数据数据字节数量
            Send_buf[3] = DDICReg;                                          // 被读取的寄存器地址
            Send_buf[4] = ReturnNumber;
            Send_buf[0] = 0x99;                                             // 通用读写
            Setting.TempRecord.cmdLen = ReturnNumber + 1 + 5;               // 返回有效数据长度+1个被读取寄存器地址+5个包头      
            CRCData.CalculateCrc16(Send_buf, out Send_buf[5], out Send_buf[6]);
            frmMain.frmain.comPort.Write(Send_buf, 0, 7);
            Thread.Sleep(100);
        }

        #region log打印设置
        private void showmsg(string str)//log打印，根据不同勾选，分类型打印log
        {
            string nowtime = DateTime.Now.Year.ToString("D4") + "-" + DateTime.Now.Month.ToString("D2") + "-" + DateTime.Now.Day.ToString("D2") + " " + DateTime.Now.Hour.ToString("D2") + ":" + DateTime.Now.Minute.ToString("D2") + ":" + DateTime.Now.Second.ToString("D2");//当前系统时间，精确到秒
            logtxtbox.SelectionStart = logtxtbox.Text.Length;
            logtxtbox.ScrollToCaret();//滚动到光标处

            if (LogTime.Checked ==true && LogPrint.Checked == true)
            {
                logtxtbox.Text += "[" + nowtime + "]:  " + str + "\r\n";
            }
            else if(LogTime.Checked == false && LogPrint.Checked == true)
            {
                logtxtbox.Text += str + "\r\n";
            }
            if (logtxtbox.Lines.Length > 3800)
            {
                Auto_save_log();
            }
        }

        private void Auto_save_log()//log自动保存
        {
            string path_log = Application.StartupPath + @"\LOG";
            string nowtime = DateTime.Now.Year.ToString("D4") + "-" + DateTime.Now.Month.ToString("D2") + "-" + DateTime.Now.Day.ToString("D2");
            if (!Directory.Exists(path_log))//如果log文件夹不存在，则new一个
            {
                Directory.CreateDirectory(path_log);
            }
            StreamWriter sw = File.AppendText(path_log + "\\" + nowtime + ".txt");
            try
            {
                sw.WriteLine(logtxtbox.Text);
                sw.Close();
                logtxtbox.Clear();
            }
            catch
            {
            }
        }

        private void logclear_Click(object sender, EventArgs e)
        {
            logtxtbox.Clear();
        }

        private void logSave_Click(object sender, EventArgs e)
        {
            if (logtxtbox.Text == string.Empty)
            {
                MessageBox.Show("--空--");
            }
            else
            {
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "Code files (*.txt)|*.txt"; 
                save.FilterIndex = 1;
                save.RestoreDirectory = true;
                if (save.ShowDialog() == DialogResult.OK)
                {
                    string path = save.FileName;
                    save.DefaultExt = ".txt";
                    StreamWriter sw = new StreamWriter(path);
                    sw.WriteLine(logtxtbox.Text);
                    sw.Close();
                }
            }
        }

        #endregion



    }
}
